package httpHandler

import (
	"context"
	"encoding/json"
	baseLog "gitee.com/zaiqiang231/go-base-app/base_app/log"
	"gitee.com/zaiqiang231/lovesport-user-service/app/store"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

func WriteResponse(c *gin.Context, code int, msg string, data interface{}) {
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  msg,
		"data": data,
	})
}

func Publish(c *gin.Context) {
	c.Next()

	if c.Writer.Status() != http.StatusOK {
		baseLog.Debugf("request failed with http status code `%d`, ignore publish message", c.Writer.Status())
		return
	}

	var resource string
	pathSplit := strings.Split(c.Request.URL.Path, "/")
	if len(pathSplit) > 1 {
		resource = pathSplit[1]
	}
	method := c.Request.Method
	switch resource {
	case "policies":
		notify(c, method, "PolicyChanged")
	case "secrets":
		notify(c, method, "SecretChanged")
	default:
	}
}

func notify(ctx context.Context, method string, command string) {
	switch method {
	case "POST", "PUT", "DELETE", "PATH":
		redisStore := store.GetRedisStore()
		message, _ := json.Marshal(Notification{Command: command})

		if err := redisStore.Publish(ctx, "lovesport.cluster.notifications", string(message)).Err(); err != nil {
			baseLog.Errorf("publish redis message failed", "error", err.Error())
		}
	default:
	}
}

type Notification struct {
	Command string `json:"command"`
}
